package com.ydy.Exception;

import com.ydy.utils.ReturnResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 异常处理类
 * @author: dy.yin 2022/1/12 15:56
 */
@RestControllerAdvice
public class MyException {

    /**
     * bean字段校验异常捕捉
     * @Title: handlerNotValidException
     * @author: dy.yin 2022/1/12 15:59
     * @return: {@link ReturnResult }
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnResult handlerNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();

        Map<String, Object> maps;
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            maps = new HashMap<>(fieldErrors.size());
            fieldErrors.forEach(error -> {
                maps.put(error.getField(), error.getDefaultMessage());
            });
        } else {
            maps = Collections.EMPTY_MAP;
        }

        return ReturnResult.errorMap(maps);
    }

    // 上传文件超过500k，捕获异常：MaxUploadSizeExceededException
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ReturnResult handlerMaxUploadFile(MaxUploadSizeExceededException ex) {
        return ReturnResult.errorMsg("文件上传大小不能超过500k，请压缩图片或者降低图片质量再上传！");
    }
}
